package com.losdun.points.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.losdun.points.controller.req.UserPointsReq;
import com.losdun.points.domain.UserPoints;
import com.losdun.points.enums.PointsTypeEnum;
import com.losdun.points.mapper.UserPointsMapper;
import com.losdun.points.service.UserPointsService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Description
 * @Author Sword.Ye
 * @Date 2025/8/18
 **/
@Service
public class UserPointsServiceImpl extends ServiceImpl<UserPointsMapper, UserPoints> implements UserPointsService {
    @Override
    public boolean checkPoints(Long wxUserId, Integer totalPoints) {
        UserPoints userPoints = this.getById(wxUserId);
        return userPoints.getAvailablePoints() >= totalPoints;
    }

    @Override
    public void updateAvaliablePoints(Long id, int nextPoint) {
        UserPoints userPoints = baseMapper.selectById(id);
        userPoints.setAvailablePoints(nextPoint);
        userPoints.setTotalPoints(userPoints.getFrozenPoints() + nextPoint);
        userPoints.setUpdateTime(LocalDateTime.now());
        baseMapper.updateById(userPoints);
    }

    @Override
    public void createAccount(Long wxUserId) {
        if(baseMapper.selectById(wxUserId)==null){
            UserPoints userPoints = new UserPoints();
            userPoints.setWxUserId(wxUserId);
            userPoints.setTotalPoints(0);
            userPoints.setAvailablePoints(0);
            userPoints.setFrozenPoints(0);
            baseMapper.insert(userPoints);
        }
    }

    @Override
    public void addPoints(Long wxUserId, int points, int type) {
        UserPoints userPoints = baseMapper.selectById(wxUserId);
        if(userPoints==null){
            throw new RuntimeException("用户积分账户不存在!");
        }
        if(PointsTypeEnum.ADD.getCode()==1){
            userPoints.setAvailablePoints(userPoints.getAvailablePoints()+points);
            userPoints.setTotalPoints(userPoints.getAvailablePoints()+userPoints.getFrozenPoints());
            userPoints.setUpdateTime(LocalDateTime.now());
        }else if(PointsTypeEnum.SUB.getCode()==2){
            userPoints.setAvailablePoints(userPoints.getAvailablePoints()-points);
            userPoints.setTotalPoints(userPoints.getAvailablePoints()+userPoints.getFrozenPoints());
            userPoints.setUpdateTime(LocalDateTime.now());
        }
        baseMapper.updateById(userPoints);
    }

    @Override
    public List<UserPoints> queryUserPointsList(UserPointsReq req) {
        return baseMapper.queryUserPointsList(req);
    }
}
